<script setup lang="ts">
import { ref, onMounted, h } from 'vue';
import { Page } from '@vben/common-ui';
import { NDataTable, NPagination, NButton, NModal, NForm, NFormItem, NInput, NSelect, NInputNumber, NTag, useMessage } from 'naive-ui';
import { getAgentList, createAgent, updateAgent, deleteAgent, getAgentDetail, publishAgent, type Agent, type AgentPublishInfo } from '#/api/agent-platform/agent';

const columns = [
  { key: 'id', title: 'ID', width: 80 },
  { key: 'name', title: 'Agent名称' },
  { key: 'custom_id', title: '自定义ID' },
  { key: 'type', title: '类型', render: (row: any) => h(NTag, { type: 'info' }, { default: () => row.type }) },
  { key: 'access_type', title: '访问类型', render: (row: any) => h(NTag, { type: row.access_type === 'public' ? 'success' : 'warning' }, { default: () => row.access_type }) },
  {
    key: 'is_published',
    title: '发布状态',
    render: (row: any) => h(NTag, {
      type: row.is_published ? 'success' : 'default'
    }, {
      default: () => row.is_published ? '已发布' : '未发布'
    })
  },
  { key: 'version', title: '版本' },
  { key: 'agent_provider_id', title: '提供商ID' },
  { key: 'created_at', title: '创建时间' },
  {
    key: 'actions',
    title: '操作',
    render(row: any) {
      return [
        h(NButton, { size: 'small', type: 'primary', onClick: () => handleDetail(row) }, { default: () => '详情' }),
        h(NButton, { size: 'small', type: 'info', class: 'ml-2', onClick: () => handleEdit(row) }, { default: () => '编辑' }),
        h(NButton, { size: 'small', type: 'success', class: 'ml-2', onClick: () => handlePublish(row), disabled: row.is_published }, { default: () => '发布' }),
        h(NButton, { size: 'small', type: 'error', class: 'ml-2', onClick: () => handleDelete(row) }, { default: () => '删除' }),
      ];
    },
  },
];

// 详情表格列定义
const detailColumns = [
  { key: 'field', title: '字段' },
  { key: 'value', title: '值' },
];

const data = ref<Agent[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const message = useMessage();

// 搜索条件
const searchForm = ref({
  keyword: '',
  agent_provider_id: undefined as number | undefined,
  type: undefined as 'agent' | 'agent_flow' | undefined,
  is_published: undefined as boolean | undefined,
});

// 弹窗相关
const showModal = ref(false);
const modalType = ref<'create'|'edit'|'detail'|'publish'>('create');
const modalTitle = ref('');
const formModel = ref<Agent>({
  name: '',
  custom_id: '',
  agent_provider_id: 0,
  type: 'agent',
  access_type: 'private',
  description: '',
  icon_url: '',
  documentation_url: '',
});
const formLoading = ref(false);
const detailData = ref<any[]>([]);

// 发布表单
const publishForm = ref<AgentPublishInfo>({
  access_type: 'private',
  version: ''
});

async function fetchData() {
  loading.value = true;
  try {
    const params: any = {
      page: page.value,
      size: pageSize.value,
      ...searchForm.value,
    };

    // 过滤掉空值
    Object.keys(params).forEach((key: string) => {
      if (params[key] === null || params[key] === '' || params[key] === undefined) {
        delete params[key];
      }
    });

    const res = await getAgentList(params);
    data.value = res.result?.items || [];
    total.value = res.result?.total || 0;
  } catch (error) {
    console.error('获取Agent列表失败:', error);
    message.error('获取Agent列表失败');
    data.value = [];
  } finally {
    loading.value = false;
  }
}

onMounted(fetchData);

function handlePageChange(p: number) {
  page.value = p;
  fetchData();
}

function handlePageSizeChange(s: number) {
  pageSize.value = s;
  page.value = 1;
  fetchData();
}

function handleSearch() {
  page.value = 1;
  fetchData();
}

function handleReset() {
  searchForm.value = {
    keyword: '',
    agent_provider_id: undefined,
    type: undefined,
    is_published: undefined,
  };
  page.value = 1;
  fetchData();
}

function handleCreate() {
  modalType.value = 'create';
  modalTitle.value = '新建Agent';
  formModel.value = {
    name: '',
    custom_id: '',
    agent_provider_id: 0,
    type: 'agent',
    access_type: 'private',
    description: '',
    icon_url: '',
    documentation_url: '',
  };
  showModal.value = true;
}

function handleEdit(row: Agent) {
  modalType.value = 'edit';
  modalTitle.value = '编辑Agent';
  formModel.value = { ...row };
  showModal.value = true;
}

async function handleDetail(row: Agent) {
  modalType.value = 'detail';
  modalTitle.value = 'Agent详情';
  formLoading.value = true;
  try {
    const res = await getAgentDetail(row.id!);
    formModel.value = res.result || {};

    // 转换为表格数据格式
    detailData.value = [
      { field: 'ID', value: formModel.value.id || '-' },
      { field: 'Agent名称', value: formModel.value.name || '-' },
      { field: '自定义ID', value: formModel.value.custom_id || '-' },
      { field: '描述', value: formModel.value.description || '-' },
      { field: '类型', value: formModel.value.type || '-' },
      { field: '访问类型', value: formModel.value.access_type || '-' },
      { field: '提供商ID', value: formModel.value.agent_provider_id || '-' },
      { field: '图标URL', value: formModel.value.icon_url || '-' },
      { field: '文档URL', value: formModel.value.documentation_url || '-' },
      { field: '访问URL', value: formModel.value.url || '-' },
      { field: '是否发布', value: formModel.value.is_published ? '是' : '否' },
      { field: '版本', value: formModel.value.version || '-' },
      { field: '发布版本', value: formModel.value.published_version || '-' },
      { field: '发布时间', value: formModel.value.publish_at || '-' },
      { field: '健康状态', value: formModel.value.current_health_status || '-' },
      { field: '拥有者ID', value: formModel.value.owner_id || '-' },
      { field: '拥有者类型', value: formModel.value.owner_type || '-' },
      { field: '创建时间', value: formModel.value.created_at || '-' },
      { field: '创建者', value: formModel.value.created_by || '-' },
    ];

    showModal.value = true;
  } catch (error) {
    console.error('获取详情失败:', error);
    message.error('获取详情失败');
  } finally {
    formLoading.value = false;
  }
}

function handlePublish(row: Agent) {
  modalType.value = 'publish';
  modalTitle.value = '发布Agent';
  formModel.value = { ...row };
  publishForm.value = {
    access_type: row.access_type || 'private',
    version: ''
  };
  showModal.value = true;
}

async function handleDelete(row: Agent) {
  if (confirm('确定要删除该Agent吗？')) {
    try {
      await deleteAgent(row.id!);
      message.success('删除成功');
      fetchData();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  }
}

async function handleModalOk() {
  formLoading.value = true;
  try {
    if (modalType.value === 'create') {
      // 验证必填字段
      if (!formModel.value.name || !formModel.value.custom_id || !formModel.value.agent_provider_id) {
        message.error('请填写Agent名称、自定义ID和提供商ID');
        return;
      }
      await createAgent(formModel.value);
      message.success('新建成功');
    } else if (modalType.value === 'edit') {
      await updateAgent(formModel.value.id!, formModel.value);
      message.success('编辑成功');
    } else if (modalType.value === 'publish') {
      // 验证发布表单
      if (!publishForm.value.version) {
        message.error('请填写发布版本');
        return;
      }
      await publishAgent(formModel.value.id!, publishForm.value);
      message.success('发布成功');
    }
    showModal.value = false;
    fetchData();
  } catch (error) {
    console.error('操作失败:', error);
    const errorMsg = modalType.value === 'create' ? '新建失败' :
                     modalType.value === 'edit' ? '编辑失败' : '发布失败';
    message.error(errorMsg);
  } finally {
    formLoading.value = false;
  }
}
</script>

<template>
  <Page description="Agent平台管理" title="Agent管理">
    <!-- 搜索条件 -->
    <div class="mb-4">
      <NForm :model="searchForm" inline>
        <NFormItem label="关键词">
          <NInput v-model:value="searchForm.keyword" placeholder="搜索名称或描述" style="width: 200px" />
        </NFormItem>
        <NFormItem label="提供商ID">
          <NInputNumber v-model:value="searchForm.agent_provider_id" placeholder="请输入提供商ID" style="width: 150px" />
        </NFormItem>
        <NFormItem label="类型">
          <NSelect
            v-model:value="searchForm.type"
            placeholder="请选择"
            :options="[
              { label: '全部', value: undefined },
              { label: 'Agent', value: 'agent' },
              { label: 'AgentFlow', value: 'agent_flow' }
            ]"
            style="width: 120px"
          />
        </NFormItem>
        <NFormItem label="发布状态">
          <NSelect
            v-model:value="searchForm.is_published"
            placeholder="请选择"
            :options="[
              { label: '全部', value: undefined },
              { label: '已发布', value: true },
              { label: '未发布', value: false }
            ]"
            style="width: 120px"
          />
        </NFormItem>
        <NFormItem>
          <NButton type="primary" @click="handleSearch">搜索</NButton>
          <NButton class="ml-2" @click="handleReset">重置</NButton>
        </NFormItem>
      </NForm>
    </div>

    <div class="mb-4 flex justify-end">
      <NButton type="primary" @click="handleCreate">新建Agent</NButton>
    </div>

    <NDataTable :columns="columns" :data="data" :loading="loading" />
    <div class="mt-4 flex justify-end">
      <NPagination
        v-model:page="page"
        v-model:page-size="pageSize"
        :item-count="total"
        show-size-picker
        :page-sizes="[10, 20, 50, 100]"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </div>

    <NModal v-model:show="showModal" :title="modalTitle" preset="dialog" :loading="formLoading" :mask-closable="false" :style="{ width: modalType === 'detail' ? '900px' : '800px' }">
      <!-- 新建/编辑表单 -->
      <NForm :model="formModel" label-width="120" v-if="modalType === 'create' || modalType === 'edit'">
        <NFormItem label="Agent名称" path="name">
          <NInput v-model:value="formModel.name" placeholder="请输入Agent名称" />
        </NFormItem>
        <NFormItem label="自定义ID" path="custom_id">
          <NInput v-model:value="formModel.custom_id" placeholder="请输入自定义ID" :disabled="modalType === 'edit'" />
        </NFormItem>
        <NFormItem label="描述" path="description">
          <NInput v-model:value="formModel.description" type="textarea" placeholder="请输入描述" />
        </NFormItem>
        <NFormItem label="类型" path="type">
          <NSelect
            v-model:value="formModel.type"
            :options="[
              { label: 'Agent', value: 'agent' },
              { label: 'AgentFlow', value: 'agent_flow' }
            ]"
            :disabled="modalType === 'edit'"
          />
        </NFormItem>
        <NFormItem label="访问类型" path="access_type">
          <NSelect
            v-model:value="formModel.access_type"
            :options="[
              { label: '私有', value: 'private' },
              { label: '公开', value: 'public' }
            ]"
          />
        </NFormItem>
        <NFormItem label="提供商ID" path="agent_provider_id">
          <NInputNumber v-model:value="formModel.agent_provider_id" placeholder="请输入提供商ID" style="width: 100%" :disabled="modalType === 'edit'" />
        </NFormItem>
        <NFormItem label="图标URL" path="icon_url">
          <NInput v-model:value="formModel.icon_url" placeholder="请输入图标URL" />
        </NFormItem>
        <NFormItem label="文档URL" path="documentation_url">
          <NInput v-model:value="formModel.documentation_url" placeholder="请输入文档URL" />
        </NFormItem>
      </NForm>

      <!-- 发布表单 -->
      <NForm :model="publishForm" label-width="120" v-else-if="modalType === 'publish'">
        <NFormItem label="Agent名称">
          <NInput :value="formModel.name" readonly />
        </NFormItem>
        <NFormItem label="当前版本">
          <NInput :value="formModel.version?.toString()" readonly />
        </NFormItem>
        <NFormItem label="访问类型" path="access_type">
          <NSelect
            v-model:value="publishForm.access_type"
            :options="[
              { label: '私有', value: 'private' },
              { label: '公开', value: 'public' }
            ]"
          />
        </NFormItem>
        <NFormItem label="发布版本" path="version">
          <NInput v-model:value="publishForm.version" placeholder="请输入发布版本，如: v1.0.0" />
        </NFormItem>
      </NForm>

      <!-- 详情展示 -->
      <NDataTable v-else :columns="detailColumns" :data="detailData" :bordered="false" />

      <template #action v-if="modalType !== 'detail'">
        <NButton type="primary" :loading="formLoading" @click="handleModalOk">确定</NButton>
        <NButton class="ml-2" @click="() => (showModal = false)">取消</NButton>
      </template>
      <template #action v-else>
        <NButton @click="() => (showModal = false)">关闭</NButton>
      </template>
    </NModal>
  </Page>
</template>

<style scoped></style>
